package com.example.smartgreenhouse.controller;

import com.example.smartgreenhouse.annotation.JwtToken;
import com.example.smartgreenhouse.annotation.Limit;
import com.example.smartgreenhouse.entity.ThresholdHistory;
import com.example.smartgreenhouse.entity.ThresholdSettings;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.utils.ResponseWrapper;
import com.example.smartgreenhouse.service.ThresholdService;
import lombok.Data;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/gsas/api/v1/thresholds")
public class ThresholdController {

    private final ThresholdService thresholdService;

    // 构造器注入（Spring Boot 2.6.13 支持省略 @Autowired）
    public ThresholdController(ThresholdService thresholdService) {
        this.thresholdService = thresholdService;
    }

    /**
     * type 的值：{soil_moisture,air_temperature,air_humidity,light_intensity}
     */
    @PostMapping("/{type}")
    @Limit(
            key = "setThreshHolds",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> setThreshold(
            @PathVariable String type,
        @RequestBody ThresholdRequest request) {

        String operator = request.getOperator() != null && !request.getOperator().isEmpty()
                ? request.getOperator()
                : "系统";
        try {
            ThresholdSettings settings = thresholdService.setThreshold(
                    type,
                    request.getMinValue(),
                    request.getMaxValue(),
                    operator
            );
            String message = "设置" + type + "的适宜区间的成功";
            return ResponseEntity.ok(ResponseWrapper.success(message, settings));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }


    @GetMapping("/history/{type}")
    @Limit(
            key = "getHistoryThreshold",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<?> getHistory(@PathVariable String type) {
        try {
            List<ThresholdHistory> history = thresholdService.getHistoryByType(type);
            return ResponseEntity.ok(history);

        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @JwtToken //表示需要Token认证。
    @GetMapping("/latest/{type}")
    @Limit(
            key = "latestThresholds",                // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.USER,        // 限流策略（按IP限流）
            msg = "查询过于频繁，请稍后重试。"            // 超限后的提示信息
    )
    public ResponseEntity<?> getLatest(@PathVariable String type) {
        try{
            ThresholdSettings setting = thresholdService.getCurrentThreshold(type);
            return ResponseEntity.ok(setting);
        }catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    // 请求参数类
    @Data
    private static class ThresholdRequest {

        private int minValue;

        private int maxValue;

        private String operator;

    }
}